package com.shiro.test.controller;

import com.shiro.sdk.properties.JwtProperties;
import com.shiro.sdk.token.JwtAuthenticationToken;
import com.shiro.sdk.utils.JwtUtil;
import com.shiro.test.response.Response;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@Slf4j
@RestController
@RequestMapping("/")
public class IndexController {
    @Resource
    private JwtProperties jwtProperties;

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public Response<String> login(String username, String password){
        String token = new JwtUtil(jwtProperties).sign(username, password);
        JwtAuthenticationToken jwtAuthenticationToken = new JwtAuthenticationToken(token);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(jwtAuthenticationToken);
            return new Response<String>().success(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("登录失败，用户名[{}]", username, e);
            return new Response<String>().fail("登录失败", e.getMessage());
        }
    }

    /**
     * 无需做权限控制的接口
     * */
    @RequestMapping(value = "anon", method = RequestMethod.POST)
    public Response<String> anon(){
        return new Response<String>().success(null);
    }

    /**
     * 需要登录才能访问的接口
     * */
    @RequiresAuthentication
    @RequestMapping(value = "/require", method = RequestMethod.POST)
    public Response<String> require(){
        return new Response<String>().success(null);
    }

    /**
     * 需要相关角色才能访问的接口
     * */
    @RequiresRoles(value = {"user"})
    @RequestMapping(value = "/role", method = RequestMethod.POST)
    public Response<String> role(){
        return new Response<String>().success(null);
    }

    /**
     * 需要相关权限才能访问的接口
     * */
    @RequiresPermissions(value = {"edit"})
    @RequestMapping(value = "/permission", method = RequestMethod.POST)
    public Response<String> permission(){
        return new Response<String>().success(null);
    }
}
